package SocketTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
    public static void main(String[] args) {
        String hostName = "127.0.0.1";
        int post = 1024;
        Scanner scanner = new Scanner(System.in);
        Socket socket= null;
        try {
            //建立连接
            socket = new Socket(hostName,post);
            //获取socket输出流
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            //获取输入流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String userIn;
            System.out.println("请输入消息:");
            //输入exit结束
            while (!"exit".equals(userIn = scanner.nextLine())){
                printWriter.write(userIn);
                System.out.println("服务端回应消息:"+bufferedReader.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
